<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form ref="userFormRef" :model="form" label-width="6em" :rules="rules">
      <el-row>
        <!-- 用户id -->
        <el-col :span="24">
          <el-form-item :label="$t('sysUser.userId')" prop="userId">
            <el-select
              v-model="form.userId"
              :placeholder="$t('sysUser.userIdRequired')"
              clearable
              filterable
              :filter-method="handleFilterMethod"
            >
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="handleLabelJoin(item)"
                :value="item.userId"
                @click="handleClick(item)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 目录id -->
        <el-col :span="24">
          <el-form-item :label="$t('sysUser.directory')" prop="directoryId">
            <el-select
              v-model="form.directoryId"
              :placeholder="$t('sysUser.directoryRequired')"
              clearable
              filterable
              allow-create
            >
              <el-option
                v-for="item in directoryList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
import { useI18n } from "vue-i18n";
import { type FormInstance, type FormRules } from "element-plus";
import { userApi } from "@/api/system/user";
import type { UserModel, UserPlatformAddReq } from "@/api/system/user/types";
import { useUserStoreHook, vueMetaEnv } from "jmash-core";
import { userLogUser } from "@/api/system/userLog";
const { t } = useI18n();
const userFormRef = ref<FormInstance>();
const model = defineModel<boolean>();
const userStore = useUserStoreHook();
let form: UserPlatformAddReq = reactive({
  requestId: Math.random() * 10 + "",
  userId: "",
  directoryId: "",
  platformTenant: vueMetaEnv.APP_TENANT,
  tenant: userStore.user.tenant,
});
// 目录id列表
const directoryList = ref();
userApi.getDirectoryApi().then(({ data }) => {
  directoryList.value = data.directoryId;
});
// 平台用户列表
const userList = ref<UserModel[]>();
const findPage = (loginName = "") => {
  userApi.findPageOrganTenant({ loginName }).then(({ data }) => {
    userList.value = data.results;
  });
};
findPage();

let timeout: number;

const handleLabelJoin = (item: UserModel) => {
  if (item.realName || item.mobilePhoneIns) {
    return item.nickName + `(${item.realName || item.mobilePhoneIns})`;
  } else {
    return item.nickName;
  }
};
// 过滤方法
const handleFilterMethod = (value: string) => {
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    console.log(value, "=> value");
    findPage(value);
  }, 300);
};

// 选中用户
const handleClick = (item: UserModel) => {
  form.directoryId = item.directoryId;
};

const rules = reactive<FormRules<UserPlatformAddReq>>({
  userId: {
    required: true,
    message: t("sysUser.userIdRequired"),
    trigger: "change",
  },
  directoryId: {
    required: true,
    message: t("sysUser.directoryRequired"),
    trigger: "change",
  },
});
const emits = defineEmits(["refresh"]);
// 提交表单校验
const submitForm = async () => {
  userFormRef.value?.validate((valid) => {
    if (!valid) return;

    userApi.createUserAdd(form).then((res) => {
      console.log(res, "=> ");
      if (res.status === 200) {
        ElMessage({
          message: t("common.submitSuccess"),
          type: "success",
        });
        if (model.value) {
          model.value = false;
        }
        emits("refresh", res.status === 200);
      }
    });
  });
};

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}
</script>
